package com.strelitzia.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strelitzia.entity.MusicEntity;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.MusicService;
import com.strelitzia.vo.MusicForm;
import com.strelitzia.vo.MusicItem;
import com.strelitzia.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @create 2024/1/19 10:57
 */

@RestController
@RequestMapping("/music")
public class MusicController {
    @Autowired
    private MusicService musicService;

    @PostMapping()
    public ResultVo add(MultipartFile file) {
        ResultVo resultVo = new ResultVo();
        try {
            musicService.add(file);
            resultVo.setMsg("上传成功");
        } catch (StrelitziaException e) {
            resultVo.setCode(1);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }

    @GetMapping("/copy/{id}")
    public ResultVo add(@PathVariable("id") Integer id) {

        ResultVo resultVo = new ResultVo();
        try {
            musicService.copy(id);
        } catch (Exception e) {
            resultVo.setCode(1);
            if (e instanceof StrelitziaException) {
                resultVo.setMsg(e.getMessage());
            }else {
                resultVo.setMsg("服务器错误");
            }
        }
        return resultVo;
    }

    @GetMapping("/del/{id}")
    public void del(@PathVariable("id") Integer id) {
        musicService.removeById(id);
    }

    @GetMapping("/list")
    public ResultVo list() {
        ResultVo resultVo = new ResultVo();
        try {
            resultVo.setData(musicService.getList());
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }

        return resultVo;
    }

    @GetMapping("/list/{id}")
    public ResultVo list(@PathVariable("id") Integer id) {
        ResultVo resultVo = new ResultVo();
        try {
            resultVo.setData(musicService.getList(id));
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }

        return resultVo;
    }

    @GetMapping("/default/{id}")
    public void setDefault(@PathVariable("id") Integer id) {
        MusicEntity one = musicService.getOne(new QueryWrapper<MusicEntity>().eq("uid", CorsFilter.loginUserId.get()).eq("weight", 1));
        if (one != null) {
            one.setWeight(0);
            musicService.updateById(one);
        }
        MusicEntity musicEntity = musicService.getById(id);
        musicEntity.setWeight(1);
        musicService.updateById(musicEntity);
    }

    @PostMapping("/edit")
    public void edit(MusicForm musicForm) {

        musicService.edit(musicForm);

    }
}
